package com.huanledoudizhu.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanledoudizhu.controller.result.ResponseResult;
import com.huanledoudizhu.controller.result.ResultCode;
import com.huanledoudizhu.entity.User;
import com.huanledoudizhu.entity.bean.VerificationCode;
import com.huanledoudizhu.mapper.UserMapper;
import com.huanledoudizhu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huanledoudizhu
 * @since 2022-11-13
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    VerificationCode verificationCode;
    @Value("${spring.mail.username}")
    private String sendMailer;

    private ResponseResult getResponseResult(User authUser) {
        SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
        String token = saTokenInfo.getTokenValue();
        long tokenTimeout = saTokenInfo.getTokenTimeout();
        HashMap<Object, Object> res = new HashMap<>();
        res.put("token", token);
        res.put("tokenTimeout", tokenTimeout);
        res.put("info", authUser);
        return new ResponseResult(ResultCode.SUCESS, res);
    }


    //注册业务
    public ResponseResult register(User user, int code, BindingResult bindingResult){
        user.setRole("1");
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (int i = 0; i < fieldErrors.size(); i++){
                System.out.println(fieldErrors.get(i).getDefaultMessage());
//                前端不显示错误信息，后端也不会抛出异常
            }
            //错就返回一个错误类型 正确就返回一个正确类型
            return new ResponseResult(ResultCode.PARAM_IS_INVALID, "");
        }
        if(userMapper.selectByEmail(user.getEmail())!=null){
            return new ResponseResult(ResultCode.USER_HAS_EXISTED,"该用户已存在");
        }
        ResponseResult responseResult = verification(user.getEmail(),code);
        if(responseResult.getCode()!=1){
            return responseResult;
        }
//        if(userMapper.insertUser(user.getUsername(),user.getEmail(),user.getPassword(),role)!=1){
//            return new ResponseResult(ResultCode.SQL_ERR,"插入失败"); mybatis残党 没用
//        }
        save(user);//修改数据库用户必须登录
        StpUtil.login(user.getId());
        String basepath = System.getProperty("user.dir");//获取项目路径
        String userPath = basepath + "\\src\\main\\resources\\file\\" +user.getId();
        java.io.File path = new java.io.File(userPath);
        if (!path.exists()) {
            path.mkdirs();
        }
        return getResponseResult(user);
    }


//bindingResult是接收前一个参数的出错的校验信息
    public ResponseResult login(User user, BindingResult bindingResult){
        String email = user.getEmail();
        String password = user.getPassword();
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (int i = 0; i < fieldErrors.size(); i++){
                System.out.println(fieldErrors.get(i).getDefaultMessage());
            }
            return new ResponseResult(ResultCode.PARAM_IS_INVALID, "");
        }
        User getUser = userMapper.selectByEmailAndPassword(email, password);
        if (getUser == null) {
            return new ResponseResult(ResultCode.USER_LOGIN_ERROR);
        }
        //这个是token
        StpUtil.login(getUser.getId());
//这里在测试
        getUser.setPassword("退！退！退！");
        String basepath = System.getProperty("user.dir");//获取项目路径
        String userPath = basepath + "\\src\\main\\resources\\file\\" +getUser.getId();
        java.io.File path = new java.io.File(userPath);
        if (!path.exists()) {
            path.mkdirs();
        }
        return getResponseResult(getUser);
    }

    public ResponseResult sendCodeToEmail(User user, BindingResult bindingResult){
        if (user.getEmail()==null || user.getEmail().trim().equals("")){
            return new ResponseResult(ResultCode.FAILURE,"");
        }
        this.verificationCode = new VerificationCode(getVerificationCode(),new Date().getTime() + 120000, user.getEmail());//两分钟验证码过期

        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(),true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(user.getEmail());
            //邮件主题
            mimeMessageHelper.setSubject("地主云盘-验证码");
            //邮件内容
            mimeMessageHelper.setText("<html><body><h4>您的验证码为：</h4><h1>"+this.verificationCode.getCode()+"</h1></body></html>", true);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());

            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功："+sendMailer+"->"+user.getEmail());
            return new ResponseResult(ResultCode.SUCESS,"");
        } catch (Exception e) {
            System.out.println("发送邮件失败："+e.getMessage());
            return new ResponseResult(ResultCode.FAILURE,"");
        }
    }

    public ResponseResult verification(String email, int code){
        if (this.verificationCode==null||this.verificationCode.getEmail()==null||!this.verificationCode.getEmail().equals(email)){
            return new ResponseResult(ResultCode.ERFICATION_EAL_ERROR);
        }
//        验证
        if (new Date().getTime()>=this.verificationCode.getDate()){
            return new ResponseResult(ResultCode.VERFICATION_CODE_EXPIRED);
        }
        if(code==this.verificationCode.getCode()){
            return new ResponseResult(ResultCode.SUCESS);
        }
        return new ResponseResult(ResultCode.VERFICATION_CODE_ERR);
    }

    public ResponseResult emailLogin(User user, int code){
        ResponseResult responseResult = verification(user.getEmail(), code);
        if(responseResult.getCode()!=1){
            return responseResult;
        }
        if(this.sendMailer==null){
            return new ResponseResult(ResultCode.FAILURE);
        }
        User user2 = userMapper.selectByEmail(this.sendMailer);        if (user2==null){
            return new ResponseResult(ResultCode.USER_NOT_EXIST);
        }
        StpUtil.login(user2.getId());
        user2.setPassword("退！退！退！");
        String basepath = System.getProperty("user.dir");//获取项目路径
        String userPath = basepath + "\\src\\main\\resources\\file\\" +user2.getId();
        java.io.File path = new java.io.File(userPath);
        if (!path.exists()) {
            path.mkdirs();
        }                       
        return getResponseResult(user2);
    }

    public int getVerificationCode(){
        int j = 0;
        for (int i = 0; i < 6; i++){
            j = j*10+(int)(10*(Math.random()));
        }
        return j;
    }


}
